//
//  LBProgressView.m
//  LBProgressView
//
//  Created by LINAICAI on 2018/4/2.
//

#import "LBProgressView.h"
#import <Masonry/Masonry.h>
#import <LBCoreKit/LBCoreKit.h>
#import "LBProgressSlider.h"
@interface LBProgressView()
@property (nonatomic , strong)NSArray<NSString *> *titles;
@property (nonatomic , assign)NSUInteger selectIndex;


///进度文本
@property (nonatomic , strong)NSMutableArray<UIButton *> *titleLabels;



///操作区域容器
@property (nonatomic , strong)UIView *contentView;
///进度按钮
@property (nonatomic , strong)NSMutableArray<UIButton *> *titleButtons;
///进度条
@property (nonatomic , strong)LBProgressSlider *slider;
@end
@implementation LBProgressView
- (LBProgressSlider *)slider{
    if (!_slider) {
        _slider = [[LBProgressSlider alloc]init];
        _slider.minimumValue = 0.0;
        _slider.maximumValue = 1.0;
        _slider.backgroundColor = [UIColor gray];
        _slider.tintColor = [UIColor blue];
        

    }
    return _slider;
}
- (UIView *)contentView{
    if (!_contentView) {
        _contentView = [UIView new];
    }
    return _contentView;
}
- (NSMutableArray<UIButton *> *)titleLabels{
    if (!_titleLabels) {
        _titleLabels = [NSMutableArray<UIButton *> new];
    }
    return _titleLabels;
}
- (NSMutableArray<UIButton *> *)titleButtons{
    if (!_titleButtons) {
        _titleButtons = [NSMutableArray<UIButton *> new];
    }
    return _titleButtons;
}
- (instancetype)initWithTitle:(NSArray<NSString *> *)titles frame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        _titles = titles;
        _selectIndex = 0;
        _maxSelectIndex = titles.count - 1;
        [self setupUI];
        [self setSelectIndex:_selectIndex];
    }
    return self;
}

- (void)setupUI{
    ///操作容器
    [self addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(20);
        make.right.mas_offset(-20);
        make.height.mas_equalTo(40);
        make.bottom.equalTo(self.mas_centerY).offset(10);
    }];
    
    ///进度条
    [self.contentView addSubview:self.slider];
    [self.slider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(30);
        make.right.mas_offset(-30);
        make.centerY.equalTo(self.contentView);
    }];
    
    ///进度标签按钮组
    for (NSString *title in self.titles) {
        UIButton *label = [UIButton buttonWithType:UIButtonTypeCustom];
        [label setTitle:title forState:UIControlStateNormal];
        [label setTitleColor:[UIColor lightBlue] forState:UIControlStateSelected];
        [label setTitleColor:[UIColor black] forState:UIControlStateNormal];
        label.titleLabel.font = [UIFont systemFontOfSize:15];
        label.selected = (self.selectIndex == [self.titles indexOfObject:title]);
        [label addTarget:self action:@selector(labelClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:label];
        [self.titleLabels addObject:label];
    }
//    [self.titleLabels mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
//                           withFixedSpacing:20
//                                leadSpacing:5
//                                tailSpacing:5];
//    [self.titleLabels mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.contentView.mas_bottom).offset(-5);
//
//    }];
    ///交互按钮组
    WS(weakSelf)
    [self.titles enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button setImage:[UIImage imageNamed:@"LBProgressView.bundle/lb_user_me_verify_nomal"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:@"LBProgressView.bundle/lb_user_me_verify_highlighted"] forState:UIControlStateHighlighted];
        [button setImage:[UIImage imageNamed:@"LBProgressView.bundle/lb_user_me_verify_highlighted"] forState:UIControlStateSelected];
        button.selected = (weakSelf.selectIndex == [weakSelf.titles indexOfObject:obj]);
        [button addTarget:weakSelf action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
        [weakSelf.contentView addSubview:button];
        [weakSelf.titleButtons addObject:button];
        button.tag = idx + 100;
    }];
    [self.slider layoutIfNeeded];
    [self.titleButtons mas_distributeViewsAlongAxis:MASAxisTypeHorizontal
                                  withFixedSpacing:(self.slider.bounds.size.width - self.titles.count*50)/(self.titles.count-1)
                                       leadSpacing:-10
                                       tailSpacing:-10];
    [self.titleButtons mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(self.contentView);
        
    }];
    
    [self.titleLabels enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIButton *titleButton = (UIButton *)[weakSelf viewWithTag:idx + 100];
        [obj mas_makeConstraints:^(MASConstraintMaker *make) {
            CGFloat offset = 0;
            if (0 == idx) {
                offset = 8;
            }
            else if (weakSelf.titles.count - 1 == idx) {
                offset = -8;
            }
            make.top.mas_equalTo(titleButton.mas_bottom).offset(-5);
        make.centerX.mas_equalTo(titleButton.mas_centerX).offset(offset);
        }];
    }];
}

- (void)labelClick:(UIButton *)button {
    ///获取点击的按钮索引
    NSUInteger index = [self.titleLabels indexOfObject:button];
    
    [self buttonClickWithIndex:index];
}

- (void)buttonClick:(UIButton *)button{
    ///获取点击的按钮索引
    NSUInteger index = [self.titleButtons indexOfObject:button];
    
    [self buttonClickWithIndex:index];
}

- (void)buttonClickWithIndex:(NSUInteger)index {
    if (!self.canGoback) {
        return;
    }
    
    if (index > _maxSelectIndex) {
        return;
    }
    
    _selectIndex = index;
    [self resetLabel];
    
    !self.select ? :self.select(index);
}

- (void)setupSlider:(NSUInteger)index animated:(BOOL)animated{
    ///分成(self.titles-1)*2格
    NSUInteger count = (self.titles.count-1)*2;
    ///每一格占slider多少进度
    CGFloat percent = 1.0/count;
    
    if (index == (self.titleButtons.count-1)) {
        ///最后一个占全部1.0
        [UIView animateWithDuration:.25 animations:^{
            [self.slider setValue:1.0 animated:animated];
        }];
        
    }
    else if (index == (self.titleButtons.count-1)) {
        ///第一个占一格
        [UIView animateWithDuration:.25 animations:^{
        [self.slider setValue:percent animated:animated];
        }];
    }
    else{
        ///第x个按钮占x-0.5格
        [UIView animateWithDuration:.25 animations:^{
        [self.slider setValue:percent*(index*2+1) animated:animated];
        }];
    }
}
- (void)setSelectIndex:(NSUInteger)selectIndex animated:(BOOL)animated{
    ///外部调用
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self setupSlider:selectIndex animated:animated];
        _selectIndex = selectIndex;
        [self resetButton];
        [self resetLabel];
    });
    
}
- (void)layoutSubviews{
    [super layoutSubviews];
    self.contentView.layer.cornerRadius = self.contentView.bounds.size.height/2.0;
    self.contentView.layer.masksToBounds = YES;
}
- (void)resetLabel{
    for (UIButton *button in self.titleLabels) {
        button.selected = (self.selectIndex == [self.titleLabels indexOfObject:button]);
    }
}
- (void)resetButton{
    for (UIButton *button in self.titleButtons) {
        NSUInteger index = [self.titleButtons indexOfObject:button];
        if (index == self.selectIndex) {
            [button setImage:[UIImage imageNamed:@"LBProgressView.bundle/lb_user_me_verify_highlighted"] forState:UIControlStateSelected];
        }
        else {
            [button setImage:[UIImage imageNamed:@"LBProgressView.bundle/lb_user_me_verify_done"] forState:UIControlStateSelected];
        }
        button.selected = (self.selectIndex >= index);
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
